package edu.ucsd.ccdb.servlet;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RunCheckRuntimeCommand {
	public static void runCommand(String cmd, StringBuffer debugBuff)throws Exception	  {
		
		long start = System.currentTimeMillis();
		System.out.println("--running--" + cmd );
		Process proc =Runtime.getRuntime().exec(cmd);

	    StringBuffer buff = new StringBuffer();
	    InputStream inputstream = proc.getInputStream();
	    InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
	    BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

	    // read the ls output
	    String line;
    	while ((line = bufferedreader.readLine()) != null) {
    		System.out.println(line);
            buff.append(line+"<br>\n");
            debugBuff.append(line+"<br>\n");
        }

    	// check for ls failure
    	try {
    		if (proc.waitFor() != 0){
				String error = "exit value = " +
									proc.exitValue()+"<br>\n";
				System.err.println(error);
				debugBuff.append(error);
				throw new Exception("Convert process failed:"+buff.toString());
	          }
	    }
    	catch (InterruptedException e) {
    		e.printStackTrace();
            StackTraceElement[] ste = e.getStackTrace();
            for(int i=0;i<ste.length;i++)
            {
            	String temp = ste[i].toString();
                debugBuff.append(temp+"<br>\n");
            }
    	}

    	long end = System.currentTimeMillis();
	    double timeInSec = ((double)(end-start))/1000;

	    System.out.println("Runtime: "+timeInSec);                  
	  }
}
